package com.pro01.apirednote.controller;

import com.pro01.apirednote.dto.LoginResponse;
import com.pro01.apirednote.dto.UserInfoResponse;
import com.pro01.apirednote.dto.UserSummaryDTO;
import com.pro01.apirednote.pojo.PageResult;
import com.pro01.apirednote.pojo.Result;
import com.pro01.apirednote.pojo.User;
import com.pro01.apirednote.mapper.UserMapper;
import com.pro01.apirednote.service.UserService;
import com.pro01.apirednote.utils.JwtUtil;
import com.pro01.apirednote.utils.Md5Util;
import com.pro01.apirednote.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final UserMapper userMapper;

    // 注册接口
    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        if (userService.existsByUsername(user.getUsername())) {
            return Result.error("用户名已存在");
        }
        // 加密密码
        user.setPassword(Md5Util.getMD5String(user.getPassword()));
        userService.register(user);
        return Result.success();
    }

    // 登录接口
    @PostMapping("/login")
    public Result<LoginResponse> login(@RequestBody User user) {
        User dbUser = userService.findByUsername(user.getUsername());
        if (dbUser == null) {
            return Result.error("用户不存在");
        }
        if (!Md5Util.checkPassword(user.getPassword(), dbUser.getPassword())) {
            return Result.error("密码错误");
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", dbUser.getId());
        claims.put("role", dbUser.getRole());

        String token = JwtUtil.genToken(claims);
        LoginResponse response = new LoginResponse(token, dbUser.getRole());
        return Result.success(response);
    }

    // 获取当前用户信息
    @GetMapping("/me")
    public Result<UserInfoResponse> getCurrentUser(HttpServletRequest request) {
        Long userId = TokenUtil.getUserId(request);
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 获取扩展数据
        Integer contentCount = userMapper.countContentsByUser(userId);
        Integer commentCount = userMapper.countCommentsByUser(userId);
        Integer totalViewCount = userMapper.countTotalViewsByUserId(userId);
        Integer receivedCommentCount = userMapper.countReceivedComments(userId);
        Integer receivedLikeCount = userMapper.sumReceivedLikes(userId);

        // 封装为响应 DTO
        UserInfoResponse dto = new UserInfoResponse();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setRole(user.getRole());
        dto.setCreatedAt(user.getCreatedAt());
        dto.setContentCount(contentCount != null ? contentCount : 0);
        dto.setCommentCount(commentCount != null ? commentCount : 0);
        dto.setTotalViewCount(totalViewCount != null ? totalViewCount : 0);
        dto.setReceivedCommentCount(receivedCommentCount != null ? receivedCommentCount : 0);
        dto.setReceivedLikeCount(receivedLikeCount != null ? receivedLikeCount : 0);

        return Result.success(dto);
    }

    // 查询用户列表
    @GetMapping("/all")
    public Result<PageResult<UserSummaryDTO>> getAllUsers(@RequestParam(defaultValue = "1") int pageNum,
                                                          @RequestParam(defaultValue = "10") int pageSize) {
        PageResult<UserSummaryDTO> pageResult = userService.listAllUsers(pageNum, pageSize);
        return Result.success(pageResult);
    }

    // 退出登录接口
    @PostMapping("/logout")
    public Result<Void> logout() {
        // 实际上什么也不做，返回成功
        return Result.success();
    }
}
